<template>
  <div>
    <div class="search">
      <input
        type="text"
        placeholder="输入城市名或拼音"
        class="search-input"
        v-model="keyword"
      />
    </div>
    <div class="search-content" ref="list" v-show="keyword">
      <ul>
        <li
          v-for="item of list"
          :key="item.id"
          class="search-item border-bottom"
          @click="handleChangeCity(item.name)"
        >
          {{ item.name }}
        </li>
        <li class="search-item border-bottom" v-show="listLengthNo">
          没有找到匹配项
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from "better-scroll";
export default {
  name: "CitySearch",
  props: {
    cities: Object,
  },
  data() {
    return {
      keyword: "",
      list: [],
      timer: null,
    };
  },
  // 当search-content组件中的列表项被点击后，执行store中的mutations中的change方法；
  // 跳转到首页并将keyword设置为''，如果keyword为空,则不显示search-content组件
  methods: {
    handleChangeCity(city) {
      this.$store.commit("change", city);
      this.$router.push("/");
      this.keyword='';
    },
  },
  // 当页面加载完毕创建一个search-content组件DOM的Bscroll实例
  mounted() {
    this.scroll = new Bscroll(this.$refs.list,{click:true});
  },
  // 如果list数组不为空则不显示“没有找到匹配项”
  computed: {
    listLengthNo() {
      return !this.list.length;
    },
  },
  // 设置侦听器，当搜索框的输入内容发生改变时执行keyword()方法
  // 设置result为输入拼音或汉字索引后返回的城市列表；将result赋值给list
  watch: {
    keyword() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      if (!this.keyword) {
        this.list = [];
        return;
      }
      this.timer = setTimeout(() => {
        const result = [];
        for (let k in this.cities) {
          this.cities[k].forEach((value) => {
            if (
              value.spell.indexOf(this.keyword) > -1 ||
              value.name.indexOf(this.keyword) > -1
            ) {
              result.push(value);
            }
          });
        }
        this.list = result;
        this.timer = null;
      }, 100);
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/assets/style/varibles.scss";
.search {
  height: 0.72rem;
  background-color: $bgColor;
  padding: 0 0.1rem;
  .search-input {
    box-sizing: border-box;
    height: 0.62rem;
    line-height: 0.62rem;
    width: 100%;
    text-align: center;
    border-radius: 0.06rem;
    color: #666;
    padding: 0 0.1rem;
  }
}
.search-content {
  z-index: 1;
  position: absolute;
  top: 1.58rem;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
  background-color: #eee;
  .search-item {
    line-height: 0.62rem;
    padding-left: 0.2rem;
    color: #666;
    background-color: #fff;
  }
}
</style>